import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';

import { IReceiveAddr, ReceiveAddr } from 'app/shared/model/receive-addr.model';
import { ReceiveAddrService } from './receive-addr.service';

@Component({
  selector: 'jhi-receive-addr-update',
  templateUrl: './receive-addr-update.component.html',
})
export class ReceiveAddrUpdateComponent implements OnInit {
  isSaving = false;

  editForm = this.fb.group({
    id: [],
    receiveName: [],
    receivePhone: [],
    receiveAddr: [],
  });

  constructor(protected receiveAddrService: ReceiveAddrService, protected activatedRoute: ActivatedRoute, private fb: FormBuilder) {}

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(({ receiveAddr }) => {
      this.updateForm(receiveAddr);
    });
  }

  updateForm(receiveAddr: IReceiveAddr): void {
    this.editForm.patchValue({
      id: receiveAddr.id,
      receiveName: receiveAddr.receiveName,
      receivePhone: receiveAddr.receivePhone,
      receiveAddr: receiveAddr.receiveAddr,
    });
  }

  previousState(): void {
    window.history.back();
  }

  save(): void {
    this.isSaving = true;
    const receiveAddr = this.createFromForm();
    if (receiveAddr.id !== undefined) {
      this.subscribeToSaveResponse(this.receiveAddrService.update(receiveAddr));
    } else {
      this.subscribeToSaveResponse(this.receiveAddrService.create(receiveAddr));
    }
  }

  private createFromForm(): IReceiveAddr {
    return {
      ...new ReceiveAddr(),
      id: this.editForm.get(['id'])!.value,
      receiveName: this.editForm.get(['receiveName'])!.value,
      receivePhone: this.editForm.get(['receivePhone'])!.value,
      receiveAddr: this.editForm.get(['receiveAddr'])!.value,
    };
  }

  protected subscribeToSaveResponse(result: Observable<HttpResponse<IReceiveAddr>>): void {
    result.subscribe(
      () => this.onSaveSuccess(),
      () => this.onSaveError()
    );
  }

  protected onSaveSuccess(): void {
    this.isSaving = false;
    this.previousState();
  }

  protected onSaveError(): void {
    this.isSaving = false;
  }
}
